// 导入请求工具类
const { request, get, post } = require("../../utils/request");

Page({
  data: {
    dates: [],
    selectedDate: "",
    todayDate: "",
    clickedIndex: null,
    timeSlots: [], // 后面动态生成
    courts: [], // 场地列表数据
    selectedCourt: null,
    selectedTimes: [], // 选中的时段数组
    totalPrice: 0,
    selectedHours: 0,
    userInfo: null, // 用户信息，登录后加载
    userOrders: [], // 用户已有订单
  },

  onLoad: function () {
    // 初始化日期和时间槽
    this.updateDateList();
    this.generateTimeSlots();
    this.fetchCourts();

    // 尝试加载用户信息，但不强制登录
    const app = getApp();
    const loginStatus = app.checkLoginStatus();
    if (loginStatus.isLoggedIn) {
      this.setData({
        userInfo: loginStatus.userInfo,
      });
      // 获取用户已有订单
      this.getUserOrders();
    }
  },

  onShow: function () {
    // 检查用户信息是否有更新
    const app = getApp();
    const loginStatus = app.checkLoginStatus();

    if (loginStatus.isLoggedIn) {
      // 如果用户信息有变化，更新本地数据
      if (
        !this.data.userInfo ||
        JSON.stringify(this.data.userInfo) !==
          JSON.stringify(loginStatus.userInfo)
      ) {
        this.setData({
          userInfo: loginStatus.userInfo,
        });
      }
      // 每次显示页面时都重新获取用户订单
      this.getUserOrders();
    }

    // 刷新场地状态
    this.fetchCourts();

    // 如果存在选择但返回到此页面，清除选择状态
    if (this.data.selectedCourt !== null) {
      this.setData({
        selectedCourt: null,
        selectedTimes: [],
        totalPrice: 0,
        selectedHours: 0,
      });
    }
  },

  updateDateList: function () {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const day = today.getDate();
    const weekday = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][
      today.getDay()
    ];
    const todayDate = `${month}.${day}`;
    const selectedDate = `${year}-${String(month).padStart(2, "0")}-${String(
      day
    ).padStart(2, "0")} ${weekday}`;

    const dates = [];
    for (let i = 0; i < 10; i++) {
      const newDate = new Date(today.getTime() + i * 24 * 60 * 60 * 1000);
      const newMonth = newDate.getMonth() + 1;
      const newDay = newDate.getDate();
      const newWeekday = [
        "周日",
        "周一",
        "周二",
        "周三",
        "周四",
        "周五",
        "周六",
      ][newDate.getDay()];
      dates.push({
        date: `${newMonth}.${newDay}`,
        weekday: newWeekday,
      });
    }

    this.setData({ dates, selectedDate, todayDate, clickedIndex: 0 }); // 默认选中当天
  },

  changeDate: function (e) {
    const index = e.currentTarget.dataset.index;
    const date = e.currentTarget.dataset.date;
    const weekday = e.currentTarget.dataset.weekday;

    // 组装日期格式
    const currentYear = new Date().getFullYear();
    const month = date.split(".")[0].padStart(2, "0");
    const day = date.split(".")[1].padStart(2, "0");
    const selectedDate = `${currentYear}-${month}-${day} ${weekday}`;

    this.setData({ selectedDate, clickedIndex: index });
    this.fetchCourts(); // 切换日期时刷新场地信息
  },

  generateTimeSlots: function () {
    const startHour = 7;
    const endHour = 22;
    const interval = 30; // 每30分钟
    const slots = [];

    for (let h = startHour; h <= endHour; h++) {
      ["00", "30"].forEach((min) => {
        if (h === endHour && min !== "00") return;
        slots.push({
          time: `${h < 10 ? "0" + h : h}:${min}`,
          courts: [], // 初始为空数组，后续根据实际场地数量填充
        });
      });
    }
    this.setData({ timeSlots: slots });
  },

  fetchCourts: function () {
    // 使用request.js中的get方法发起请求
    get("/court/list", {
      pageNum: 1,
      pageSize: 100,
    })
      .then((res) => {
        const courtList = res.data.list || [];

        // 保存场地列表
        this.setData({ courts: courtList });

        // 获取当天的所有订单，用于更新场地状态
        this.fetchDateOrders();
      })
      .catch((err) => {
        console.error("获取场地列表失败:", err);
      });
  },

  // 获取当天所有场地的订单
  fetchDateOrders: function () {
    // 获取当前选择的日期
    const dateStr = this.data.selectedDate.split(" ")[0]; // 2023-05-15 格式

    // 请求特定日期的所有订单
    get("/order/date", { date: dateStr })
      .then((res) => {
        if (res.code === 200) {
          const orders = res.data || [];

          // 更新时间槽中的场地状态
          const updatedSlots = this.updateTimeSlotsWithOrders(
            this.data.courts,
            orders
          );
          this.setData({ timeSlots: updatedSlots });
        } else {
          console.error("获取订单失败:", res.message);
          // 如果获取订单失败，仍然初始化场地状态
          const updatedSlots = this.updateTimeSlotsWithCourts(this.data.courts);
          this.setData({ timeSlots: updatedSlots });
        }
      })
      .catch((err) => {
        console.error("获取订单失败:", err);
        // 如果获取订单失败，仍然初始化场地状态
        const updatedSlots = this.updateTimeSlotsWithCourts(this.data.courts);
        this.setData({ timeSlots: updatedSlots });
      });
  },

  // 根据场地列表更新时间槽数据
  updateTimeSlotsWithCourts: function (courtList) {
    // 获取场地数量
    const courtCount = courtList.length;

    // 更新时间槽，为每个时间点创建与场地数量匹配的状态数组
    return this.data.timeSlots.map((slot) => ({
      ...slot,
      courts: Array(courtCount).fill(0), // 0: 可约, 1: 已约, 2: 被占用, 3: 不可约
    }));
  },

  // 根据订单更新时间槽数据
  updateTimeSlotsWithOrders: function (courtList, orders) {
    // 获取场地数量
    const courtCount = courtList.length;

    // 初始化时间槽状态数组
    const slots = this.data.timeSlots.map((slot) => ({
      ...slot,
      courts: Array(courtCount).fill(0), // 默认所有场地为可约
    }));

    // 检查每个订单，根据状态更新场地可用性
    orders.forEach((order) => {
      const courtId = order.courtId;
      const startTime = new Date(order.startTime);
      const endTime = new Date(order.endTime);

      // 找到场地在数组中的索引
      const courtIndex = courtList.findIndex((court) => court.id === courtId);
      if (courtIndex === -1) return; // 如果找不到场地，跳过

      // 处理每个时间段
      slots.forEach((slot, slotIndex) => {
        // 提取时间点的小时和分钟
        const [hours, minutes] = slot.time.split(":").map(Number);
        const slotDate = new Date(this.data.selectedDate.split(" ")[0]);
        slotDate.setHours(hours, minutes, 0, 0);

        // 判断时间段是否与订单重叠
        if (slotDate >= startTime && slotDate < endTime) {
          // 根据订单状态标记场地状态
          if (order.status === "used") {
            // 已使用的订单：标记为被占用
            slots[slotIndex].courts[courtIndex] = 2;
          } else {
            // 其他状态：标记为已约
            slots[slotIndex].courts[courtIndex] = 1;
          }
        }
      });
    });

    // 检查当前时间，标记过期时间段为不可约
    const now = new Date();
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();
    const dateStrParts = this.data.selectedDate.split(" ")[0].split("-");
    const selectedDate = new Date(
      dateStrParts[0],
      dateStrParts[1] - 1,
      dateStrParts[2]
    );
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    // 如果选择的是今天或过去的日期
    if (selectedDate.getTime() <= today.getTime()) {
      // 处理每个时间段
      slots.forEach((slot, slotIndex) => {
        const [slotHour, slotMinute] = slot.time.split(":").map(Number);

        // 如果时间段已过，标记为不可约
        if (
          slotHour < currentHour ||
          (slotHour === currentHour && slotMinute <= currentMinute)
        ) {
          for (let i = 0; i < courtCount; i++) {
            slots[slotIndex].courts[i] = 3; // 不可约
          }
        }
      });
    }

    return slots;
  },

  selectCourt: function (e) {
    const { timeIndex, courtIndex, courtStatus } = e.currentTarget.dataset;
    const timeSlot = this.data.timeSlots[timeIndex];
    const court = this.data.courts[courtIndex];
    const cellStatus = timeSlot.courts[courtIndex];

    // 检查场地状态，如果是维修中则不可选
    if (court.status === 0) {
      wx.showToast({
        title: "该场地维修中",
        icon: "none",
      });
      return;
    }

    // 检查场地是否已被预约或其他状态
    if (cellStatus === 1) {
      wx.showToast({
        title: "该场地此时段已被预约",
        icon: "none",
      });
      return;
    }

    // 检查场地是否被占用
    if (cellStatus === 2) {
      wx.showToast({
        title: "该场地此时段已被占用",
        icon: "none",
      });
      return;
    }

    // 检查场地是否不可约
    if (cellStatus === 3) {
      wx.showToast({
        title: "该时段已过期，不可预约",
        icon: "none",
      });
      return;
    }

    // 获取选中场地的信息
    if (!court) {
      wx.showToast({
        title: "场地信息有误",
        icon: "none",
      });
      return;
    }

    // 检查是否已选择该时间段，如果是则取消选择
    if (
      this.data.selectedCourt === courtIndex &&
      this.data.selectedTimes.includes(timeIndex)
    ) {
      this.setData({
        selectedCourt: null,
        selectedTimes: [],
        totalPrice: 0,
        selectedHours: 0,
      });
      return;
    }

    // 标记选中的时间段和球场
    this.setData({
      selectedCourt: courtIndex,
      selectedTimes: [timeIndex],
      totalPrice: Number(court.price).toFixed(2), // 格式化价格显示
      selectedHours: 0.5,
    });

    // 提示用户选择成功
    wx.showToast({
      title: "已选择时间段",
      icon: "success",
      duration: 800,
    });
  },

  submitReservation: function () {
    // 检查是否选择了场地和时间
    if (!this.data.selectedCourt && this.data.selectedTimes.length === 0) {
      wx.showToast({
        title: "请选择时间段",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    // 确保选择了有效的场地
    if (
      this.data.selectedCourt === null ||
      typeof this.data.selectedCourt !== "number"
    ) {
      wx.showToast({
        title: "请重新选择场地",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    // 检查登录状态
    const app = getApp();
    const loginStatus = app.checkLoginStatus();

    if (!loginStatus.isLoggedIn) {
      // 未登录则先跳转到登录页面
      wx.showToast({
        title: "请先登录",
        icon: "none",
        duration: 1500,
      });

      setTimeout(() => {
        app.navigateToLogin();
      }, 1500);
      return;
    }

    const timeIndex = this.data.selectedTimes[0];
    const timeSlot = this.data.timeSlots[timeIndex];
    const startTime = timeSlot.time;
    const endTime = this.calculateEndTime(startTime, 30); // 默认半小时

    // 获取选中场地的信息
    const courtIndex = this.data.selectedCourt;
    const court = this.data.courts[courtIndex];

    if (!court) {
      wx.showToast({ title: "场地信息有误", icon: "none" });
      return;
    }

    // 获取日期
    const dateStr = this.data.selectedDate.split(" ")[0]; // 2023-05-15 格式
    const [year, month, day] = dateStr.split("-");

    // 构建完整的开始和结束时间
    const fullStartTime = `${dateStr} ${startTime}:00`;
    const fullEndTime = `${dateStr} ${endTime}:00`;

    // 检查用户是否有时间冲突的订单
    if (this.checkTimeConflict(fullStartTime, fullEndTime)) {
      wx.showModal({
        title: "时间冲突",
        content: "您在所选时间段内已有预约，是否继续预约？",
        confirmText: "继续预约",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            // 用户确认继续预约
            this.showOrderConfirmation(
              court,
              dateStr,
              startTime,
              endTime,
              fullStartTime,
              fullEndTime
            );
          }
        },
      });
      return;
    }

    // 显示订单确认
    this.showOrderConfirmation(
      court,
      dateStr,
      startTime,
      endTime,
      fullStartTime,
      fullEndTime
    );
  },

  // 显示订单确认弹窗
  showOrderConfirmation: function (
    court,
    dateStr,
    startTime,
    endTime,
    fullStartTime,
    fullEndTime
  ) {
    wx.showModal({
      title: "确认预约",
      content: `您将预约:\n场地: ${court.name}\n时间: ${startTime}-${endTime}\n日期: ${dateStr}\n费用: ¥${court.price}`,
      confirmText: "确认预约",
      confirmColor: "#2d4581",
      success: (res) => {
        if (res.confirm) {
          // 用户点击确认，提交订单
          this.createOrder(court, fullStartTime, fullEndTime, court.price);
        }
      },
    });
  },

  // 获取用户已有订单
  getUserOrders: function () {
    const app = getApp();
    const loginStatus = app.checkLoginStatus();

    if (!loginStatus.isLoggedIn) {
      return;
    }

    const userId = loginStatus.userInfo.id;

    // 获取用户订单
    get(`/order/user/${userId}`, {})
      .then((res) => {
        if (res && res.data) {
          // 将订单信息保存到本地，以便在预约时检查冲突
          const userOrders = res.data.list || [];

          // 检查是否有未完成的订单，有则提示用户
          const unfinishedOrders = userOrders.filter(
            (order) => order.status === "normal" && order.payStatus === "unpaid"
          );

          if (unfinishedOrders.length > 0) {
            wx.showModal({
              title: "未完成订单",
              content: "您有未支付的订单，是否前往查看?",
              confirmText: "去查看",
              cancelText: "继续预约",
              success: (result) => {
                if (result.confirm) {
                  wx.navigateTo({
                    url: "/pages/myorder/myorder",
                  });
                }
              },
            });
          }

          // 存储订单信息
          this.setData({
            userOrders: userOrders,
          });
        }
      })
      .catch((err) => {
        console.error("获取用户订单失败:", err);
      });
  },

  // 格式化日期时间为MySQL兼容格式
  formatDateTime: function (date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    const seconds = date.getSeconds().toString().padStart(2, "0");

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  // 创建订单
  createOrder: function (court, startTime, endTime, price) {
    // 显示加载提示
    wx.showLoading({
      title: "创建订单中...",
      mask: true,
    });

    const app = getApp();
    const loginStatus = app.checkLoginStatus();

    // 获取当前时间作为创建和更新时间
    const now = new Date();
    const createTime = this.formatDateTime(now);

    // 准备订单数据
    const orderData = {
      userId: Number(loginStatus.userInfo.id), // 确保是数字类型
      courtId: Number(court.id), // 确保是数字类型
      startTime: startTime,
      endTime: endTime,
      totalAmount: parseFloat(price), // 确保价格是数字类型，后端会转为BigDecimal
      payStatus: "unpaid", // 默认未支付状态
      status: "normal", // 默认正常状态
    };

    console.log("订单数据:", orderData);

    // 先测试日期格式
    this.testDateFormat(orderData);

    // 发送创建订单请求
    post("/order/create", orderData)
      .then((res) => {
        wx.hideLoading();
        // 创建成功后显示成功提示
        wx.showToast({
          title: "预约成功",
          icon: "success",
          duration: 2000,
        });

        // 重置选择状态
        this.setData({
          selectedCourt: null,
          selectedTimes: [],
          totalPrice: 0,
          selectedHours: 0,
        });

        // 刷新场地状态
        this.fetchCourts();

        // 提示用户查看订单
        setTimeout(() => {
          wx.showModal({
            title: "预约成功",
            content: "您已成功预约场地，是否立即查看订单?",
            confirmText: "查看订单",
            cancelText: "继续预约",
            success: (result) => {
              if (result.confirm) {
                // 跳转到订单详情页
                wx.navigateTo({
                  url: "/pages/myorder/myorder",
                });
              }
            },
          });
        }, 1500);
      })
      .catch((err) => {
        wx.hideLoading();
        console.error("提交预约失败:", err);

        // 显示具体错误信息，方便调试
        console.error("请求数据:", JSON.stringify(orderData));
        console.error("错误详情:", JSON.stringify(err));

        wx.showModal({
          title: "预约失败",
          content: err.message || "创建订单时发生错误，请稍后重试",
          showCancel: false,
        });
      });
  },

  // 测试日期格式
  testDateFormat: function (orderData) {
    console.log("测试日期格式...");

    // 发送请求到测试接口
    post("/order/test-date-format", orderData)
      .then((res) => {
        console.log("日期格式测试成功:", res);
      })
      .catch((err) => {
        console.error("日期格式测试失败:", err);
        console.error("请求数据:", JSON.stringify(orderData));
        console.error("错误详情:", JSON.stringify(err));

        // 显示错误提示
        wx.showModal({
          title: "日期格式错误",
          content: JSON.stringify(err.message || "日期格式测试失败"),
          showCancel: false,
        });
      });
  },

  // 验证订单数据
  validateOrderData: function (orderData) {
    // 检查用户ID
    if (!orderData.userId) {
      return { valid: false, message: "用户ID不能为空" };
    }

    // 检查场地ID
    if (!orderData.courtId) {
      return { valid: false, message: "场地ID不能为空" };
    }

    // 检查状态字段
    if (!orderData.status) {
      return { valid: false, message: "订单状态不能为空" };
    }

    // 检查支付状态
    if (!orderData.payStatus) {
      return { valid: false, message: "支付状态不能为空" };
    }

    // 检查时间格式
    const timeRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
    if (!timeRegex.test(orderData.startTime)) {
      return { valid: false, message: "开始时间格式不正确" };
    }
    if (!timeRegex.test(orderData.endTime)) {
      return { valid: false, message: "结束时间格式不正确" };
    }
    if (!timeRegex.test(orderData.createTime)) {
      return { valid: false, message: "创建时间格式不正确" };
    }
    if (!timeRegex.test(orderData.updateTime)) {
      return { valid: false, message: "更新时间格式不正确" };
    }

    // 检查开始时间是否早于结束时间
    const start = new Date(orderData.startTime);
    const end = new Date(orderData.endTime);
    if (start >= end) {
      return { valid: false, message: "结束时间必须晚于开始时间" };
    }

    // 检查金额是否合法
    if (orderData.totalAmount === undefined || orderData.totalAmount === null) {
      return { valid: false, message: "订单金额不能为空" };
    }

    if (isNaN(orderData.totalAmount) || orderData.totalAmount <= 0) {
      return { valid: false, message: "金额必须为正数" };
    }

    return { valid: true };
  },

  calculateEndTime: function (start, minutes) {
    const [h, m] = start.split(":").map(Number);
    const totalMins = h * 60 + m + minutes;
    const endH = Math.floor(totalMins / 60);
    const endM = totalMins % 60;
    return `${endH < 10 ? "0" + endH : endH}:${endM === 0 ? "00" : endM}`;
  },

  // 检查时间冲突
  checkTimeConflict: function (startTime, endTime) {
    // 如果没有获取到用户订单，则不做检查
    if (!this.data.userOrders || this.data.userOrders.length === 0) {
      return false;
    }

    const start = new Date(startTime);
    const end = new Date(endTime);

    // 检查与现有订单是否有时间冲突
    return this.data.userOrders.some((order) => {
      // 只检查正常状态的订单
      if (order.status !== "normal") {
        return false;
      }

      const orderStart = new Date(order.startTime);
      const orderEnd = new Date(order.endTime);

      // 检查是否有重叠
      return start < orderEnd && end > orderStart;
    });
  },
});
